﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;

using Outcoder;
using Outcoder.Logging;
using Outcoder.UserOptionsModel;
using Outcoder.UI.Xaml;

namespace CalciumTemplateApp
{
	/// <summary>
	/// This content control selects the template to use for displaying a user option.
	/// </summary>
	public class OptionTemplateSelector : ContentControl
	{
		readonly Dictionary<string, DataTemplate> templateLookup
						= new Dictionary<string, DataTemplate>();

		FrameworkElement resoucesOwner;
		protected override void OnContentChanged(object oldContent, object newContent)
		{
			DataTemplate template = GetDefaultContentTemplate();
			if (newContent != null)
			{
				IUserOptionReaderWriter writer = newContent as IUserOptionReaderWriter;
				if (writer != null)
				{
					string templateName = writer.UserOption.TemplateName;
					if (!string.IsNullOrWhiteSpace(templateName))
					{
						template = GetTemplate(templateName);
					}
					else
					{
						templateName = writer.UserOption.GetType().Name;
						template = GetTemplate(templateName);

						if (template == null)
						{
							ILog log;
							if (Dependency.TryResolve<ILog>(out log))
							{
								log.Error("A default template was not found for the IUserOption of type:" + templateName);
							}

							if (Debugger.IsAttached)
							{
								Debugger.Break();
							}
						}
					}
				}
			}

			ContentTemplate = template;
		}

		DataTemplate GetTemplate(string templateName)
		{
			DataTemplate template;

			if (!templateLookup.TryGetValue(templateName, out template))
			{
				if (resoucesOwner == null)
				{
					resoucesOwner = this.GetAncestorOrSelf<ListBox>();
				}
				//var parentElement = (FrameworkElement)Parent;
				template = (DataTemplate)resoucesOwner.Resources[templateName];
				if (template != null)
				{
					templateLookup[templateName] = template;
				}
			}

			return template;
		}

		protected virtual DataTemplate GetDefaultContentTemplate()
		{
			return null;
		}
	}
}